// common/request.js
import urlConfig from './config.js'
import store from '@/store';
const request = {}
const headers = {
		'content-type': 'application/json;charset=utf-8'
	}

request.globalRequest = (url, method, data, power) => {
  switch (power) {
    case 1:
      headers['user-info'] = `${store.getters.getToken}`
      break
    case 2:
      headers['user-info'] = `${store.getters.getToken}`
      break
    case 3:
      headers['user-info'] = `${store.getters.getToken}`
      headers['responseType'] = 'blob'
      break
    default:
      break
  }
  // 如果 data 是 FormData 类型，则不设置 Content-Type，让浏览器自动处理
  if (!(data instanceof FormData)) {
    headers['content-type'] = 'application/json;charset=utf-8';
  }

  return uni.request({
    url: urlConfig + url,
    method: method,
    data: data,
    dataType: 'json',
    header: headers
  }).then(res => {
    // if (res[1].data.status || res[1].data.code === 200) {
    //   return res[1].data
    // } else {
    //   throw res[1].data
    // }
    return res[1].data 
  }).catch(params => {
    switch (params.code) {
      case 401:
        uni.clearStorageSync()
        break
      default:
        uni.showToast({
          title: params.message,
          icon: 'none'
        })
        return Promise.reject()
        break
    }
  })
}

export default request